package com.mashibing.juc.c_026_01_ThreadPool;

import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: Yuanzt
 * @Date: 2021/4/2
 */
public class T05_00_HelloThreadPool {
    static class Task implements Runnable{
        private int i;
        public Task(int i){
            this.i = i;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " Task " + i);
            try {
                System.in.read();//阻塞
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public String toString() {
            return "Task{" +
                    "i=" + i +
                    '}';
        }
    }

    public static void main(String[] args) {
        /*核心线程数:corePoolSize
        最大线程数:maximumPoolSize
            最大线程数=核心线程数+非核心线程数
        生存时间:keepAliveTime
        时间单位:TimeUnit
        任务队列:BlockingQueue
        线程工厂
        拒绝策略*/

        /*
        拒绝策略：
            Abort抛异常、
            Discard：扔掉，不抛异常、
            DiscartOldest：扔掉排队时间最久的、
            CallerRuns调用者处理任务
         */
        ThreadPoolExecutor tpe = new ThreadPoolExecutor(2,4,60, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(4),
                Executors.defaultThreadFactory(),
//                new ThreadPoolExecutor.AbortPolicy()); //报异常
//                new ThreadPoolExecutor.DiscardPolicy()); //悄悄扔掉
//                new ThreadPoolExecutor.CallerRunsPolicy()); //谁提交任务谁来执行
                new ThreadPoolExecutor.DiscardOldestPolicy()); //扔掉最长等待时间的
        for (int i = 0; i < 8; i++) {
            tpe.execute(new Task(i));
        }

        System.out.println(tpe.getQueue());

        tpe.execute(new Task(100));

        System.out.println(tpe.getQueue());

        tpe.shutdown();
    }
}
